<style>
    .el-table .audited-row {
        background: #fde1d2;
    }
    .yhgl-container .el-pagination{
        margin-top: 5px !important;
    }
    .flfg-viewor .el-dialog__body{
        padding-top: 1px;
    }
    .yhgl-container .el-tree-node.is-expanded{
        width: max-content !important;
    }
    .bhxj-check-box span.el-checkbox-button__inner{
        padding-left: 10px;
        padding-right: 10px;
        border-radius: 4px !important;
    }
    .yhgl-container .ces-table{
        margin-bottom: 0 !important;
    }
</style>
<template>
    <div class="table">
        <div class="container custome-container" style="padding: 10px 15px;padding-top: 2px;padding-bottom:0;">
            <div class="handle-box custome-handle-box" style="margin: 0;margin-bottom: 3px !important;">
                <el-form ref="form">
                    <el-row>
                        <el-col :span="2" style="margin-top: 2px;">
                            <el-checkbox-group class="bhxj-check-box" v-model="bhxjChecked" @change="bhxjChanged" size="small">
                                <el-checkbox-button size="mini">包含下级</el-checkbox-button>
                            </el-checkbox-group>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="姓名">
                                <el-input v-model="select_word" style="width: 70%;" placeholder="请输入姓名"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="6">
                            <el-form-item label="角色">
                                <el-select v-model="fk_roles_pk" filterable placeholder="请选择角色名称" style="width: 70%">
                                    <el-option v-for="item in dics.roles" :key="item.role_pk" :label="item.role_name" :value="item.role_pk"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4">
                            <el-form-item>
                                <el-button type="primary" icon="el-icon-search" @click="search" style="background:#3a8ee6;color:#fff;">查询</el-button>
                                <el-button type="primary" icon="el-icon-refresh-right" @click="reset" style="background:rgb(177, 5, 5);color:#fff;border:rgb(177, 5, 5)">重置</el-button>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-container class="yhgl-container" :style="{height:containerHeight+'px',border:'0px solid #eee',marginRight:'-15px',marginBottom:'1px'}">
                <el-aside width="23%" style="border-right: 1px solid rgb(235, 238, 245);background:#f8f8f8;margin-left:-15px;margin-bottom: -1px;">
                    <el-tree ref='userJgTree'
                             :load="loadNode"
                             lazy
                             :data="optionData"
                              node-key="organ_pk"
                             @node-click="handleNodeClick"
                             @check-change="handleCheckChange"
                             :check-strictly="true"
                             show-checkbox
                             :props="defaultProps">
                    </el-tree>
                </el-aside>
                <el-container>
                    <el-main style="padding:0 0 5px 0;margin:0px 0;margin-bottom:0;">
                        <div class="handle-box" style="margin-bottom: 0;padding: 0 0 0 11px;">
                            <el-button type="primary" size="mini" icon="el-icon-lx-add" @click="add" style="background:#fff;border:1px solid #3a8ee6;color:#3a8ee6;">添加</el-button>
                            <el-button type="primary" size="mini" icon="el-icon-lx-edit" @click="edit" style="background:#fff;border:1px solid #3a8ee6;color:#3a8ee6;">编辑</el-button>
                            <el-button type="primary" size="mini" icon="el-icon-lx-emoji" @click="qyTy('1')" style="background:#fff;border:1px solid #3a8ee6;color:#3a8ee6;">启用</el-button>
                            <el-button type="primary" size="mini" icon="el-icon-lx-emojifill" @click="qyTy('0')" style="background:#fff;border:1px solid #3a8ee6;color:#3a8ee6;">停用</el-button>
                            <el-button type="primary" size="mini" icon="el-icon-delete" @click="deleteRow" style="background:#fff;border:1px solid #3a8ee6;color:#3a8ee6;">删除</el-button>
                        </div>
                        <ces-table id="table" ref="cestable" size='mini'
                                   :that='that'
                                   :stripe="true"
                                   :isIndex='true'
                                   :isHandle='true'
                                   :isSelection='false'
                                   :radio-selection="true"
                                   :isPagination='true'
                                   :tableData='tableData'
                                   :tableCols='tableCols'
                                   :tablePage='pagination'
                                   :tableHeight='tableHeight'
                                   @handleSizeChange="handleSizeChange"
                                   @handleCurrentChange='handleCurrentChange'
                                   @handleSelectionChange='handleSelectionChange'
                        >
                        </ces-table>
                    </el-main>
                </el-container>
            </el-container>
            <!--编辑页面-->
            <cesEdit :visible="editor.visible" :data="editor.data" :titleName="editor.titleName" ref="zzjgTree"></cesEdit>
        </div>
    </div>
</template>
<script>
    import cesTable from '../../../common/Table'
    import cesEdit from './edit'
    import aesjjm from "../../../../util/aes/aesjjm";

    export default {
        name: "user",
        components: {
            cesTable, cesEdit
        },
        //弹出页面保存完数据后调用该页面的pages方法刷新列表数据
        provide() {
            return {
                refresh: this.refresh, 
                dateFormatYMD: this.dateFormatYMD, 
                disableKey: this.disableKey
            }
        },
        data() {
            return {
                that: this,
                node_id: '999',//树形目录的根节点id
                tableHeight: window.innerHeight - 252,
                containerHeight: window.innerHeight - 170,
                upQTS: '/auth/user/upQTS',
                url_organ: '/auth/organ/list',
                url_page: '/auth/user/pages',
                url_del: '/auth/user/delete',
                url_delAll: '/auth/user/delAll',
                tree_lazy_url:'/auth/organ/tree_organ_lazy_list',
                tree_url: '/jggl/organTree/getOrganTree',//获取机构数据
                // 表头及字段
                tableCols: [
                    {label: '姓名', prop: 'user_name', width: 120,},
                    {label: '性别', render: (h, params) => {return h('span', params.row.user_sex === '1' ? '男' : '女')}, width: 50,},
                    {label: '登录名', prop: 'user_loginname', width: 120,},
                    {label: '登录密码', prop: 'user_password', width: 120,},
                    {label: '角色名称', render: (h, params) => this.renderDict(h, params, 'fk_role_pk'), width: 150,},
                    // {label: '角色名称', prop: 'fk_role_pk', width: 200,},
                    // {label: '机构名称', prop: 'fk_organ_pk', width: 200,},
                    {label: '角色名称', render: (h, params) => this.renderOrgan(h, params, 'fk_organ_pk'), width: 150,},
                    {label: '联系电话', prop: 'user_phone', width: 100,},
                    {label: '身份证号', prop: 'user_idcard', width: 150,},
                    {
                        label: '用户状态',
                        width: 100,
                        render: (h, params) => {
                            let style = {};
                            if (params.row.user_status === '1') {
                                style.color = '#42FF26';
                            } else {
                                style.color = '#FF1524';
                            }
                            return h('span', {style: style}, params.row.user_status === '1' ? '启用' : '停用')
                        }
                    },
                    {label: '录入时间', prop: 'user_intime', width: 100,},
                ],
                tableData: [],//表格数据
                multipleSelection:[],
                pagination: {pageSize: 20, pageNum: 1, total: 20},
                usersInfo:[],
                form: {
                    page: '1',//第几页
                    limit: '10',//每页条数，默认10条
                    bpd074: ''
                },
               data:{
                 organ_pk: '',
                 organ_parent: '',
               },
                dics: {},
                editor: {
                    titleName: '', visible: false, data: {dics: {}}
                },
                viewor: {
                    visible: false, flfgPk: ''
                },
                disableEnterKey: false,
                inTreeDataEdit: false,
                defaultProps: {
                    value: 'organ_pk', // ID字段名
                    label: 'organ_name', // 显示名称
                    children: 'children', // 子级字段名
                    levl: 'levl',// 机构等级
                },
                bhxjChecked: '',/*包含下级*/
                logindXzqhLevl: '',
                select_word: '',
                fk_roles_pk: '',
                logindXzqh: '',
                treeData: [],
                treeList: [],
                select_jgid: '',
            }
        },
        created() {
            this.initDict();//加载字典
            this.getPages();//加载查询方法
 /*           this.$nextTick(function () {
                // this.initTreeData();
            });*/
            this.logindXzqh = this.$getDict("XZQH").filter(item => item.dict_code === localStorage.getItem("ms_qhdm"))[0];
            // this.logindXzqhLevl = this.logindXzqh['dict_level'];
        },
        methods: {
            //变更分页条数
            handleSizeChange(val) {
                this.form.limit = val;
                this.getPages();//根据用户获取的每页显示页面数量显示页面
            },
            //变更上一页下一页
            handleCurrentChange(val) {
                this.form.page = val;
                this.getPages()
            },
            //选中table行
            handleSelectionChange(val) {
                if (val.length > 0) {
                    this.multipleSelection = val;
                    this.$refs.cestable.clearSelect();
                }
            },
            /*包含下级选中状态发生变化*/
            bhxjChanged(val) {
                var checkedNodes = this.$refs.userJgTree.getCheckedNodes();
                if (checkedNodes && checkedNodes.length > 0) {
                    this.doCheckedWuery(checkedNodes[0]);
                }
            },
            /*选中状态改变事件*/
            handleCheckChange(data, checked) {
                if (checked) {
                    this.select_jgid = data.organ_pk;
                    this.$refs.userJgTree.setCheckedKeys([this.select_jgid]);
                    this.doCheckedWuery(data);
                } else {
                    if (this.select_jgid === data.organ_pk) {
                        this.$refs.userJgTree.setCheckedKeys([]);
                        this.form.organ_name='';
                        this.getPages();
                    }

                }
            },
            /*点击事件*/
            handleNodeClick(data,checked){
              if(!checked.checked){
                this.select_jgid = data.organ_pk;
                this.$refs.userJgTree.setCheckedKeys([this.select_jgid]);
                this.doCheckedWuery(data);
              }else{
                this.$refs.userJgTree.setCheckedKeys([]);
                this.doCheckedWuery(data);
              }

            },
            /*点击查询*/
            doCheckedWuery(data) {
                var selectedId = [];
                if (data){
                    if (this.bhxjChecked) {
                        this.fillAllChildren(data, selectedId);
                    } else {
                        selectedId.push(data.organ_pk);
                    }
                }
                this.form.organ_name = selectedId.toString();
                this.getPages();
            },
            /*拼接选中机构的所有子机构*/
            fillAllChildren(data, selectedId) {
                if (data) {
                    selectedId.push(data.organ_pk);
                    if (data.children && data.children.length > 0) {
                        for (let i = 0; i < data.children.length; i++) {
                            if (data.children[i].children && data.children[i].children.length > 0) {
                                this.fillAllChildren(data.children[i], selectedId);
                            } else {
                                selectedId.push(data.children[i].organ_pk);
                            }
                        }
                    }
                }
            },
            //弹窗编辑完后刷新列表页面在子页面调用改方法
            refresh() {
                this.editor.visible = false;
                this.reset();
                this.getPages();
            },

          //懒加载机构树
          loadNode(node, resolve) {
            if (node.level === 0) {
              this.data.organ_parent=0;
            }else{
              this.data.organ_parent=node.data.organ_pk;
            }
            this.$post(this.tree_lazy_url,this.data).then(res => {
              if(res){
                return resolve(res);
              }
            })
          },

            // 获取分页数据
            getPages() {
                /*清除表格选中状态*/
                try {
                    this.multipleSelection = '';
                    this.$refs.cestable.clearRadioSelection();
                }catch (e) {/**/}
                /*请求参数*/
                this.editor.visible = false;
                this.form.limit = this.pagination.pageSize;
                this.form.user_name = this.select_word;
                this.form.user_sex = '';
                this.form.user_status = '';
                this.form.fk_roles_pk = this.fk_roles_pk;
                this.$post(this.url_page, this.form).then(res => {
                    if (res.data) {
                        this.tableData = res.data;
                        this.pagination.total = res.data.total;
                    }
                })
            },
            /*搜索查询*/
            search() {
                this.getPages();
            },
            /*重置*/
            reset() {
                /*清空查询条件*/
                this.select_word = '';
                this.fk_roles_pk = '';
                this.select_jgid = '';
                this.form.organ_name = '';
                /*清除机构树选择状态*/
                this.$refs.userJgTree.setCheckedKeys([this.select_jgid]);
            },
            add() {
                if (!this.select_jgid) {
                    this.$alert('请勾选左侧的机构!', '系统提示', {
                        confirmButtonText: '确定',
                        iconClass: 'el-icon-office-building',
                        callback: action => {
                            /**/
                        }
                    });
                    return;
                }
                this.editor.visible = true;
                this.editor.data = {user_sex: '1', user_status: '1'};//必须给form赋值，否则会报错
                this.editor.titleName = '用户(新增)';//动态设置弹框页面的标题为新增
                this.editor.data.fk_organ_pk = this.select_jgid;
                this.editor.data.optTyle = 'add';
                this.editor.data.dics = {};
            },
            /*统一行校验*/
            uniqueRowOperate() {
                if (this.multipleSelection && this.multipleSelection.length > 0) {
                    return this.multipleSelection[0];
                } else {
                    this.$message({type: 'error', message: '请选择一个用户!'});
                }
                return null;
            },
            /*行编辑*/
            edit(row) {
                row = this.uniqueRowOperate();
                if (row) {
                    this.editor.visible = true;
                    this.editor.titleName = '用户(编辑)';//动态设置弹框页面的标题为编辑
                    //todo 需要对密码进行加解密
                    // row.user_password = aesjjm.decrypt(row.user_password);
                    this.editor.data = JSON.parse(JSON.stringify(row));
                    this.editor.data.dics = {};
                    this.editor.data.optTyle = 'edit';
                }
            },
            /*起停用*/
            qyTy(val, row) {
                row = this.uniqueRowOperate();
                if (row) {
                    if (row.user_status === val) {
                        if (val === '0') {
                            this.$message({type: '', message: '用户已停用，请勿重复停用!',});
                        } else if (val === '1') {
                            this.$message({type: '', message: '用户已启用，请勿重复启用!',});
                        }
                    } else {
                        let title = '';
                        if (val === '0') {
                            title = '确定要停用该数据吗？';
                        } else if (val === '1') {
                            title = '确定要启用该数据吗？';
                        }
                        this.$confirm(title, '提示', {
                            confirmButtonText: '确定', cancleButtonText: '取消', type: 'warning'
                        }).then(() => {
                            this.$post(this.upQTS, {user_pk: row.user_pk, user_status: val}).then(res => {
                                this.$message({type: res.code, message: res.msg,});
                                this.getPages();
                            }).catch(() => {
                                this.refresh();
                            });
                        }).catch(() => {
                            this.refresh();
                        });
                    }
                }
            },
            /*单行删除*/
            deleteRow(row) {
                row = this.uniqueRowOperate();
                if (row) {
                    if (row.user_status === '0') {
                        if (row.user_pk !== '' && row.user_pk != null) {
                            this.$confirm('确定要删除数据吗？', '提示', {
                                confirmButtonText: '确定', cancleButtonText: '取消', type: 'warning'
                            }).then(() => {
                                this.$post(this.url_del, {user_pk: row.user_pk}).then(res => {
                                    this.$message({type: res.code, message: res.msg,});
                                    this.getPages();
                                }).catch(() => {
                                    this.refresh();
                                });
                            }).catch(() => {
                                this.refresh();
                            });
                        }
                    } else {
                        this.$message({type: '', message: '用户已启用，无法删除!',});
                    }
                }
            },
            /*初始化字典*/
            initDict() {
                this.dics.fk_role_pk = this.$getDict('ROLES_TYPE');//角色
                this.getOrgan();//机构

            },
            getOrgan(){
                this.$post(this.url_organ,{}).then(res => {
                    if(res){
                        this.dics.fk_organ_pk= res.data;
                    }
                })
            },
            /*渲染表格字典*/
            renderDict(h, params, field) {
                let text = '';
                this.dics[field].forEach((r) => {
                    if (r.dict_code === params.row[field]) {
                        text = r.dict_name;
                    }
                });
                return h('span', {}, text);
            },
            renderOrgan(h, params, field) {
                let text = '';
                // debugger;
                // this.dics.fk_organ_pk.forEach((r) => {
                //     if (r.organ_pk === params.row[field]) {
                //         text = r.organ_name;
                //     }
                // });
                text = this.dics.fk_organ_pk[params.row[field]]
                return h('span', {}, text);
            },
            /*渲染多个值字典*/
            // renderDictS(h, params, field) {
            //     debugger;
            //     let text = '';
            //     this.dics[field].forEach((r) => {
            //         let val = params.row[field].split(',');
            //         for (let i = 0; i < val.length; i++) {
            //           if (r.dict_code === val[i]) {
            //             text += r.dict_name + ",";
            //           }
            //         }
            //     });
            //     if (text.indexOf(",") > 0) {
            //       text = text.substr(0, text.length - 1);
            //     }
            //     return h('span', text);
            // },
            /*渲染录入人*/
    
            dateFormat(h, params, field) {
                return h('span', {}, params.row[field] ? this.dateFormatYMD(params.row[field]) : "");
            },
            dateFormatYMD(dat) {
                return this.$dateFormat(dat).format('YYYY-MM-DD HH:mm:ss');
            },
            disableKey() {
                this.disableEnterKey = false;
            },
            handleDialogClose1() {
                this.viewor.visible = false;
            },
            changeOptionData(filterd) {
                // if (filterd && filterd.length > 0) {
                //     this.expandedKeys.push(filterd[0].id);
                // }
            },
            initTreeData() {
                this.$post(this.tree_url, {id:localStorage.getItem("ms_jgId")}).then(res => {
                    if (res.data) {
                        this.treeList = res.data
                    }
                });
            }
        },
        /*全页面监听回车查询事件*/
        mounted() {
            let _this = this;
            document.onkeydown = function (e) {
                if (e.keyCode === 13 && !_this.disableEnterKey) {
                    _this.search();
                }
            }
        },
        computed: {
            /* ${树形组件}-转树形数据 */
            optionData() {
                let _this_ = this;
                //对源数据深度克隆
                let cloneData = JSON.parse(JSON.stringify(this.treeList));
                //循环所有项，并添加children属性
                let filterd = cloneData.filter(father => {
                    //返回每一项的子级数组
                    let branchArr = cloneData.filter(child => father.id === child.parentId);
                    //给父级添加一个children属性，并赋值
                    branchArr.length > 0 ? (father.children = branchArr) : '';
                    //返回第一层
                    if (_this_.logindXzqhLevl==='1'){
                        let nodeId = localStorage.getItem("ms_organPk")
                        /*for (let i = 0; i < _this_.treeList.length; i++) {
                          if (_this_.treeList[i].id=== localStorage.getItem("ms_jgId")){
                            nodeId = _this_.treeList[i].parentId
                          }
                        }*/
                        return father.parentId === nodeId
                    } else {
                        return father.xzqh === localStorage.getItem("ms_organQhdm")
                    }
                });
                this.changeOptionData(filterd);
                return filterd;
            },
        }
    };
</script>
<style scoped>
    @import "../../../../assets/css/common.css";
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>

